<?php

namespace App\Helpers;

use Hyperf\Di\Annotation\Inject;

use Hyperf\HttpServer\Contract\ResponseInterface as AAA;
use Hyperf\Utils\Context;

trait ApiResponse
{
    /**
     * @Inject
     * @var AAA
     */
    protected $response;

    protected $statusCode = ResponseCode::HTTP_OK;


    public function getStatusCode()
    {
        return $this->statusCode;
    }


    public function setStatusCode($statusCode,$httpCode=null)
    {
        $httpCode = $httpCode ?? $statusCode;

        Context::set('http_code',$statusCode);


//        $this->statusCode = $statusCode;
        return $this;
    }


    public function respond($data, $header = [])
    {
        return $this->response->json($data,Context::get('http_code',200),$header);
    }


    public function status($status, array $data, $code = null){

        if ($code){
            $this->setStatusCode($code);
        }
        $status = [
            'status' => $status,
            'code' => $this->statusCode
        ];

        $data = array_merge($status,$data);
        return $this->respond($data);

    }


    public function failed($message, $code = ResponseCode::HTTP_BAD_REQUEST,$status = 'error'){
        return $this->setStatusCode($code)->message($message,$status);
    }


    public function message($message, $status = "success")
    {
        return $this->status($status,[
            'message' => $message
        ]);
    }

    public function internalError($message = "Internal Error!"){

        return $this->failed($message,ResponseCode::HTTP_INTERNAL_SERVER_ERROR);
    }


    public function created($message = "created")
    {
        return $this->setStatusCode(ResponseCode::HTTP_CREATED)
            ->message($message);

    }


    public function success($data, $status = "success"){

        return $this->status($status,compact('data'));
    }


    public function notFond($message = 'Not Fond!')
    {
        return $this->failed($message,ResponseCode::HTTP_NOT_FOUND);
    }
}